<?php
declare(strict_types=1);

namespace Reven\Result;


class Re
{
    public $status=true;

    /**
     * 返回值数据
     * @var array|object
     */
    public $data=[];

    /**
     * 返回值描述
     * @var string
     */
    public string $msg="";

    /**
     * 返回值code
     * @var string
     */
    public string $code;

    /**
     * 协助逻辑数据
     * @var mixed
     */
    public $ld;

    /**
     * Re constructor.
     * @param bool $status
     * @param string $msg
     * @param array|mixed $data
     * @param string $code
     */
    public function __construct(bool $status,$msg="",$data=[],$code='')
    {
        $this->status=$status;
        $this->data=$data;
        $this->msg=$msg?$msg:($this->status?"success":"failed");
        $this->code=$code;
    }

    public function toArray():array {
        return [
            'code'=>$this->code,
            'msg'=>$this->msg,
            'data'=>$this->data,
            'status'=>$this->status,
        ];
    }

    public function toJson():string {
        $obj=$this->toObj();
        return json_encode($obj,512);
    }

    public function get($key){
        if (!is_array($this->data)){
            return null;
        }
        return $this->data[$key]??null;
    }

    public function toObj():\stdClass{
        $re=new \stdClass();
        $re->code=$this->code;
        $re->msg=$this->msg;
        $re->data=$this->data;
        $re->status=$this->status;
        return $re;
    }

    public function set($key,$value){
        $this->data[$key]=$value;
        return $this;
    }

    public function sets(array $keyValue){
        foreach ($keyValue as $k=>$v){
            $this->data[$k]=$v;
        }
        return $this;
    }

    public function unset(...$keys){
        foreach ($keys as $k){
            if (isset($this->data[$k])){
                unset($this->data[$k]);
            }
        }
        return $this;
    }

    public function setCode(string $code){
        $this->code=$code;
        return $this;
    }

    public function setLd($ld){
        $this->ld=$ld;
        return $this;
    }
}